<template>
  <t-dialog
    :header="header"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    @confirm="onSubmit"
    :confirmBtn="{
        content: loading?'提交中...':'确认',
        theme: 'primary',
        loading: loading,
      }"
    width="800px"
    top="5%"
  >
    <t-form ref="form" :colon="true"  :data="formData" labelWidth="100px" :rules="rules">
      <t-row style="row-gap:24px">
        <t-col :span="12">
          <t-form-item label="上级单位" name="parentId">
            <t-tree-select v-if="!isUnitAdmin" :disabled="isUnitAdmin" clearable filterable :treeProps="{keys: {value: 'id',label:'deptName'}}"
                           v-model="formData.parentId" :data="menuOptions" placeholder="选择上级单位"></t-tree-select>
            <t-input disabled v-else v-model="deptName"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="归口单位" name="managerId">
            <t-tree-select  clearable filterable :treeProps="{keys: {value: 'id'}}" v-model="formData.managerId"
                           :data="menuOptions2" placeholder="选择归口单位"></t-tree-select>
<!--            <t-input disabled v-else v-model="deptManagerName"></t-input>-->
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="单位名称" name="deptName">
            <t-input clearable v-model="formData.deptName" placeholder="请输入单位名称"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="显示排序" name="orderNum">
            <t-input-number clearable v-model="formData.orderNum" :min="1" placeholder="请输入"></t-input-number>
          </t-form-item>
        </t-col>

        <t-col :span="12">
          <t-form-item label="单位地址" name="address">
            <t-input clearable v-model="formData.address" placeholder="请输入单位地址"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="单位所在地" name="locationId">
            <t-cascader clearable filterable :keys="{value:'id'}" v-model="formData.locationId" :options="locationOptions" placeholder="请选择单位所在地"></t-cascader>
          </t-form-item>
        </t-col>

        <t-col :span="6">
          <t-form-item label="社会信用代码" name="code">
            <t-input clearable v-model="formData.code" placeholder="请输入统一社会信用代码"></t-input>
          </t-form-item>
        </t-col>

        <t-col :span="6">
          <t-form-item label="邮编" name="postCode">
            <t-input clearable v-model="formData.postCode" placeholder="请输入邮编"></t-input>
          </t-form-item>
        </t-col>

        <t-col :span="6">
          <t-form-item label="负责人" name="leader">
            <t-input clearable v-model="formData.leader" placeholder="请输入负责人"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="联系电话" name="phone">
            <t-input clearable v-model="formData.phone" placeholder="请输入联系电话"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="邮箱" name="email">
            <t-input clearable v-model="formData.email" placeholder="请输入邮箱"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="单位状态" name="status">
            <t-radio-group v-model="formData.status" :options="dict.type.sys_normal_disable">
              <!--              <t-radio value="0"  label="正常"></t-radio>-->
              <!--              <t-radio value="1" label="停用"></t-radio>-->
            </t-radio-group>
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="单位简介" name="deptProfile">
            <t-textarea :autosize="{minRows: 3}"
                        v-model="formData.deptProfile" placeholder="请输入单位简介"/>
          </t-form-item>
        </t-col>
      </t-row>
    </t-form>
  </t-dialog>
</template>

<script>
import {listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild} from "@/api/system/dept";

export default {
  name: "add-edit-unit",
  dicts: ['sys_normal_disable'],
  props: ['header', 'deptId', 'parentId'],
  data() {
    return {
      rules: {
        parentId: [
          {required: true, message: "上级单位不能为空"}
        ],
        address: [
          {required: true, message: "单位地址不能为空"}
        ],
        locationId: [
          {required: true, message: "单位所在地不能为空"}
        ],
        // code:[
        //   { required: true, message: "社会信用代码不能为空" }
        // ],
        managerId: [
          {required: true, message: "归口单位不能为空"}
        ],
        // postCode:[
        //   { required: true, message: "邮编不能为空" }
        // ],
        deptName: [
          {required: true, message: "单位名称不能为空"}
        ],
        orderNum: [
          {required: true, message: "显示排序不能为空"}
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        // phone: [
        //   {
        //     pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/,
        //     message: "请输入正确的手机号码",
        //   }
        // ]
      },
      deptName: '',
      deptManagerName: '',
      isUnitAdmin: false,
      menuOptions: [],
      menuOptions2: [],
      locationOptions: [],
      visible: true,
      loading: false,
      formData: {
        parentId: null,
        managerId: null,
        address: '',
        code: '',
        postCode: '',
        deptName: "",
        leader: "",
        phone: "",
        email: "",
        status: "0",
        orderNum: 1,
        deptProfile: '',
        locationId: '',
      }
    }
  },
  watch: {
    deptId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getObj();
        }
      }
    },
    parentId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.formData.parentId = val;
          this.formData.managerId = val;
        }
      }
    }
  },
  created() {
    if (this.deptId === 0) {
      this.getTreeselect();
      this.getTreeselectAllIn();
      this.getLocation();
    }
  },
  methods: {
    async getObj() {
      await Promise.all([this.getTreeselect(), this.getTreeselectAllIn(), this.getLocation()])
      getDept(this.deptId).then(response => {
        if (response.data.parentId === 0) {
          response.data.parentId = response.data.id;
        }
        if (response.data.managerId === 0) {
          response.data.managerId = response.data.id;
        }
        // 如果说当前单位是 列表的第一级 兼容 管理员单位
        const index = this.menuOptions.findIndex(val => this.deptId === val.id)
        if (index !== -1) {
          getDept(response.data.parentId).then(resp => {
            this.isUnitAdmin = true;
            this.deptName = resp.data.deptName;
          }).catch((e) => {
            this.$message.error(e.toString());
          });
          // getDept(response.data.managerId).then(resp => {
          //   this.deptManagerName = resp.data.deptName;
          // }).catch((e) => {
          //   this.$message.error(e.toString());
          // });
          // this.menuOptions[]
        }
        this.formData = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.loading = true;
          if (this.deptId) {
            let {parentId} = this.formData;
            if (this.deptId === this.formData.parentId) {
              parentId = 0;
            }
            const row = {...this.formData, parentId}
            updateDept(row).then((response) => {
              this.$message.success("修改成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          } else {
            let {parentId} = this.formData;
            if (!this.formData.parentId) {
              parentId = 0;
            }
            const row = {...this.formData, parentId}
            addDept(row).then((response) => {
              this.$message.success("新增成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          }
        }
      });
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
    /** 查询菜单下拉树结构 */
    getTreeselectAllIn() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.menuOptions2 = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getTreeselect() {
      return listDept().then(response => {
        this.menuOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getLocation(){
      return this.$api.system.location.treeselect().then(response => {
        this.locationOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    }
  }
}
</script>

<style scoped>
.overlay-options {
  display: inline-block;
  font-size: 20px;
}
</style>
